<?php
/**
 * Created by PhpStorm.
 * User: 小蛮哼哼哼
 * Email: 243194993@qq.com
 * Date: 2021/12/31 0031
 * Time: 17:52
 * motto: 现在的努力是为了小时候吹过的牛逼！
 */

declare(strict_types=1);


namespace app\common\business;

use app\common\model\MallGroupsOrder;
use app\common\model\MallOrder as ModelObj;
use app\common\model\MallOrderGoods;
use app\common\validate\Order as ValObj;
use think\Exception;
use think\facade\Log;

class Orders extends Base
{
    /**
     * @var ValObj
     */
    protected ValObj $valObj;
    /**
     * @var ModelObj
     */
    protected ModelObj $modelObj;

    /**
     *
     */
    public function __construct()
    {
        $this->valObj = new ValObj();
        $this->modelObj = new ModelObj();
    }

    /**
     * 查询订单信息
     * @param {Object} $ordersn
     */
    public function getByOrderId($ordersn){
        $where =[['ordersn','=',$ordersn]];

        try{
            $result=$this->modelObj->getModelByInfo($where,'*');
        }catch(\Exception $e){
            throw new Exception("系统内部错误");
        }
        return $result;
    }

    /**
     * 查询订单信息
     * @param {Object} $ordersn
     */
    public function getByOrderIds($order_id){



        $where =[['id','=',$order_id]];

        try{
            $result=$this->modelObj->getModelByInfo($where,'*');
        }catch(\Exception $e){
            throw new Exception("系统内部错误");
        }
        return $result;
    }


    /**
     * 查询订单信息
     * @param {Object} $ordersn
     */
    public function getByOrderOpenIds($order_id,$openid){
        $where =[['id','=',$order_id],['openid','=',$openid]];

        try{
            $result=$this->modelObj->getModelByInfo($where,'*');
        }catch(\Exception $e){
            throw new Exception("系统内部错误");
        }
        return $result;
    }

    /**
     * 查询订单信息
     * @param {Object} $ordersn
     * @throws Exception
     */
    public function getOrderSnByOpenid($ordersn,$openid){

        try{
            $result=$this->modelObj->alias('o')
                ->field('o.*,p.ordersn as orderno')
                ->join('member_paylog p','p.order_id=o.id')
                ->where("o.ordersn='".$ordersn."' and o.openid='".$openid."'")
                ->find();
        }catch(\Exception $e){
            throw new Exception("系统内部错误");
        }
        
        return $result;
    }


    /**
     * 下单/ 更新订单
     * @param $data
     * @return void
     * @throws Exception
     */
    public function saveData($data){
        try {
            $orderinfo =$this->modelObj->getModelByInfo([['id','=',$data['id']]],'*');
        } catch (\Exception $e) {
            throw new Exception($e->getMessage());
        }
        if($orderinfo){
            $orderinfo->save($data);
        }else{
            $this->modelObj->save($data);
        }
        return true;
    }

    /**
     * 指定订单
     * @param $openid
     * @param $type
     * @param $page
     * @return array
     * @throws Exception
     */
    public function getOrders($openid,$type,$page='1'){
        $where=[];
        if($type!='-1'){
            $where[] =[['openid','=',$openid],['orderstatus','=',$type]];
        }else{
            $where[] =[['openid','=',$openid]];
        }
        $where[] = [
            ['deleted','<>',1]
        ];
        try {
            $list= $this->modelObj
                ->field('id,ordersn,payprice,isapplyrefund,orderstatus,create_time,create_time as end_time')
                ->where($where)
                ->order('create_time desc,orderstatus ASC')
                ->page($page,10)
                ->select()
                ->toArray();

        } catch (\Exception $e) {
            throw new Exception($e->getMessage());
        }

        if($list){
            foreach ($list as $k=>$v){
                $goodslist=(new OrderGoods())->getByOrderGoodsList($v['id']);
                $list[$k]['child'] =$goodslist;
                switch($v['orderstatus']){
                    case '0':
                        $list[$k]['statusname'] ='待支付';
                        break;
                    case '1':
                        if($v['isapplyrefund']==1){
                            $list[$k]['statusname'] ='售后处理中';
                        }else{
                            $list[$k]['statusname'] ='待发货';
                        }
                        break;
                    case '2':
                        if($v['isapplyrefund']==1){
                            $list[$k]['statusname'] ='售后处理中';
                        }else{
                            $list[$k]['statusname'] ='待收货';
                        }
                        break;
                    case '3':
                        if($v['isapplyrefund']==1){
                            $list[$k]['statusname'] ='售后处理中';
                        }else{
                            $list[$k]['statusname'] ='已完成';
                        }

                        break;
                    case '4':
                        $list[$k]['statusname'] ='已退款';
                        break;
                    default:
                        $list[$k]['statusname'] ='已取消';
                        break;
                }
            }
        }

        return $list;
    }

    /**
     * 获取订单详情
     * @param $order_id
     * @param $openid
     * @return mixed
     * @throws Exception
     */
    public function getOrderInfoById($order_id,$openid){
        $where=[];
        $where[] =[['openid','=',$openid],['deleted','<>',1],['id','=',$order_id]];

        try {
            $info= $this->modelObj
                ->field('*')
                ->where($where)
                ->find();
        } catch (\Exception $e) {
            throw new Exception($e->getMessage());
        }

        if($info){
            $manager=(new MallOrderGoods())->alias('og')->field('og.manager_id,og.goods_id,m.title')
                ->join('mall_manager m','m.id=og.manager_id')
                ->where("og.order_id='$order_id'")->group('og.manager_id')->select()->toArray();
            foreach($manager as $k=>$v){
                $goodslist=(new MallOrderGoods())->alias('og')->field('og.goods_name,og.total,og.price,g.logo')
                    ->join('mall_goods g','g.id=og.goods_id')->where("og.manager_id='".$v['manager_id']."' and og.order_id='".$order_id."'")
                    ->select()->toArray();
                $manager[$k]['goods'] =$goodslist;
            }
            $info['goods'] =$manager;
            if($info['paytime']){
                $info['paytime'] =date('Y-m-d H:i:s',$info['paytime']);
            }
            if($info['shipping_time']){
                $info['shipping_time'] =date('Y-m-d H:i:s',$info['shipping_time']);
            }
            if($info['confirm_time']){
                $info['confirm_time'] =date('Y-m-d H:i:s',$info['confirm_time']);
            }
            switch($info['orderstatus']){
                case '0':
                    $info['statusname'] ='待支付';
                    break;
                case '1':
                    if($info['isapplyrefund']==1){
                        $info['statusname'] ='售后处理中';
                    }else {
                        $info['statusname'] = '待发货';
                    }
                    break;
                case '2':

                    if($info['isapplyrefund']==1){
                        $info['statusname'] ='售后处理中';
                    }else{
                        $info['statusname'] ='待收货';
                    }
                    break;
                case '3':
                    if($info['isapplyrefund']==1){
                        $info['statusname'] ='售后处理中';
                    }else{
                        $info['statusname'] ='已完成';
                    }
                    break;
                case '4':
                    $info['statusname'] ='已退款';
                    break;
                default:
                    $info['statusname'] ='已取消';
                    break;
            }
        }
        return $info;
    }

    /**
     * 执行过期订单更新
     * @param $openid
     * @return bool
     * @throws Exception
     */
    public function getOrderByAll($openid){

        try{
            $shoptime =(new Member())->getSystenConfig('shoptime');
            $endtime =time()-$shoptime*60;
            $list=$this->modelObj->field('id,ordersn,openid,paytype,deduct_price')->where("openid='$openid' and orderstatus=0 and create_time<'".$endtime."'")->select()->toArray();
        }catch(\Exception $e){
            throw new Exception($e->getMessage());
        }

        if($list){
            foreach ($list as $k=>$v){
                $this->modelObj->where("id='".$v['id']."'")->save(array('orderstatus'=>-1,'canceltime'=>time()));
                if($v['paytype']==3 && $v['deduct_price']>0){
                    // 记录钱包明细
                    (new Member())->saveAccoutLog($v['openid'], round($v['deduct_price'],2), 4, '余额退款');
                }
            }

        }
        return true;
    }


    public function getOrderByAllList(){
        try{
            $shoptime =(new Member())->getSystenConfig('shoptime');
            $endtime =time()-$shoptime*60;
            $list=$this->modelObj->field('id,openid,ordersn,paytype,deduct_price')->where("orderstatus=0 and create_time<'".$endtime."'")->select()->toArray();
        }catch(\Exception $e){
            throw new Exception($e->getMessage());
        }
        if($list){
            foreach ($list as $k=>$v){
                $this->modelObj->where("id='".$v['id']."'")->save(array('orderstatus'=>-1,'canceltime'=>time()));
                if($v['paytype']==3 && $v['deduct_price']>0){
                    // 记录钱包明细
                    (new Member())->saveAccoutLog($v['openid'], round($v['deduct_price'],2), 4, '余额退款');
                }
            }
        }
    }


}